using Light;
using UnityEngine;

//sky 24-11-24 13:56 
public class PlayerController : MonoBehaviour
{
    public AudioClip bgm;

    public float walkSpeed;
    public float runSpeed;

    private Animator _anim;

    private float _inputX;
    private float _inputY;
    private bool _isRunning;
    private Rigidbody2D _rb;


    // Start is called before the first frame update
    private void Start()
    {
        _anim = GetComponent<Animator>();
        _rb = GetComponent<Rigidbody2D>();
        AudioManager.Instance.setBGM(bgm);
    }

    // Update is called once per frame

    private void FixedUpdate()
    {
        _isRunning = LightInputManager.Instance.RunInput;
        Move();
    }

    private void Move()
    {
        _inputX = LightInputManager.Instance.NormalInputX;
        _inputY = LightInputManager.Instance.NormalInputY;

        //计算移动方向
        var moveDir = new Vector2(_inputX, _inputY).normalized;
        //移动应用
        MoveAnimSetting(moveDir);
        if (!_isRunning)
        {
            _rb.velocity = moveDir * walkSpeed;
        }
        else
        {
            _anim.SetBool("Run", true);
            _rb.velocity = moveDir * runSpeed;
        }

        if (!_isRunning)
            _anim.SetBool("Run", false);
    }

    private void MoveAnimSetting(Vector2 moveDir)
    {
        _anim.SetFloat("InputX", _inputX);
        _anim.SetFloat("InputY", _inputY);
        _anim.SetFloat("Speed", moveDir.sqrMagnitude); //sqrMagnitude方法优化后为求向量长度的方法，要比直接开平方计算开销小
    }
}